﻿<?php
class Model_Agent extends Zend_Db_Table_Abstract
{
		protected $_name = 'agent';
		protected $_primary = 'a_id';
		
		public function createAgent ($pa_id, $u_id, $a_giachapnhan, $a_time)
		{
			$rowAgent = $this->createRow();
			if ($rowAgent) {
				// update the row values
				$rowAgent->pa_id = $pa_id;
				$rowAgent->u_id = $u_id;
				$rowAgent->a_giachapnhan = $a_giachapnhan;
				$rowAgent->a_time = $a_time;
				$rowAgent->save();
				//return the new user
				return $rowAgent;
			} else {
				throw new Zend_Exception("Không thể tạo được agent! ");
			}
		}
		public static function getAgentById($a_id)
		{
			$agentModel = new self();
			$select = $agentModel->select();
			$select->order(array('a_id'))
					->where('a_id=?',$a_id);
			return $agentModel->fetchAll($select);
		}

		public static function getAgentByUserPaId($u_id,$pa_id)
		{
			$agentModel = new self();
			$select = $agentModel->select();
			$select->order(array('pa_id'))
					->where('u_id=?',$u_id)
					->where('pa_id =?',$pa_id);
			return $agentModel->fetchAll($select);
		}
		
		public static function getAgentByTime($a_time)
		{
			$agentModel = new self();
			$select = $agentModel->select();
			$select->order(array('a_time'))
					->where('a_time=?',$a_time);
			return $agentModel->fetchAll($select);
		}		
		
		public function updateAgent($a_id,$pa_id,$u_id,$a_giachapnhan,$a_time)
		{
			$where = $this->getAdapter()->quoteInto('a_id =?',$a_id);
			$set = array('pa_id' =>$pa_id,'u_id'=>$u_id,'a_giachapnhan'=>$a_giachapnhan,'a_time'=>$a_time);
			$rows_affected = $this->update($set, $where);
		}
	
		public function deleteAgent($a_id)
		{
			// fetch the user's row
			$rowAgent= $this->find($a_id)->current();
			if($rowAgent) {
				$rowAgent->delete();
			}else{
				throw new Zend_Exception("Could not delete agent.  Agent not found!");
			}
		}		

		
		public function computeTimeAgent($min, $max)
		{
			$agentModel = new self();
			$a_time =  rand($min,$max);
			$timeResult = $agentModel->getAgentByTime($a_time);
			while(count($timeResult) >0){
				$a_time =  rand($min,$max);
				$timeResult = $agentModel->getAgentByTime($a_time);
			}
			return $a_time;
		}
	
}
